﻿namespace Json2Model
{
    public class AutoSerialize<T> where T : new() 
    {
        public AutoSerialize(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("AutoSerialize.Name");
            SerializeFileName = name;
            var v = DeserializeObjForFile(name);
            if (v == null)
            {
                v = new T();
                SerializeObjToFile(_value, SerializeFileName);
            }
            _value = v;
        }

        public string SerializeFileName { get; } = string.Empty;

        private T _value;
        public T Value
        {
            get { return _value; }
            set 
            { 
                _value = value; 
                SerializeObjToFile(_value, SerializeFileName); 
            }
        }
       
        public void Save()
        {
            SerializeObjToFile(this.Value!,this.SerializeFileName);
        }
        public void SerializeObjToFile(object? obj, string fileName)
        {
            string path = Environment.CurrentDirectory;
            if (!fileName.ToLower().EndsWith(".json"))
                fileName += ".json";
            using TextWriter tw = new StreamWriter(Path.Combine(path, fileName));
            tw.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));
            tw.Close();
        }
        public T? DeserializeObjForFile(string fileName)
        {
            string path = Environment.CurrentDirectory;
            if (!fileName.ToLower().EndsWith(".json"))
                fileName += ".json";
            string fullPath = Path.Combine(path, fileName);
            if (!File.Exists(fullPath))
                return default(T);
            using StreamReader sr = new StreamReader(fullPath, Encoding.Default);
            return JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
        }
    }
}
